package cn.iune.web.backcenter.security.filters;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSONObject;

import cn.iune.common.response.ResultData;

/*
 * BACKSTAGE项目使用
 * backcenter
 * 站点过滤器和api过滤器差别：重定向到登录页面和返回json
 */

//后台管理安全控制器
@WebFilter(filterName="/backcenterSessionFilter",urlPatterns="/backcenter/*")
public class BackcenterSessionFilter implements Filter {
	
	private Logger log = LogManager.getLogger(this.getClass());
	
	private static final String LOGIN_URL = "/blogin"; 
//	private static final String LOGIN_URL = "/backcenter/unauthenticated"; 
	
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(  
            Arrays.asList("/plogin", "/logout", "/register"
            		, "/backcenter/unauthenticated"
            		
            		)));  
    
    
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {
    	
    	String contextPath = filterConfig.getServletContext().getContextPath();
    	int majorVersion = filterConfig.getServletContext().getMajorVersion();
    	int minorVersion = filterConfig.getServletContext().getMinorVersion();
    	String serverInfo = filterConfig.getServletContext().getServerInfo();
    	String servletContextName = filterConfig.getServletContext().getServletContextName();
    	int sessionTimeout = filterConfig.getServletContext().getSessionTimeout();
    	
        log.info("backcenterSessionFilter init-----------filter安全过滤器启动。。。。。。");  
        log.info("backcenterSessionFilter init-----------contextPath:"+contextPath);  
        log.info("backcenterSessionFilter init-----------majorVersion:"+majorVersion);  
        log.info("backcenterSessionFilter init-----------minorVersion:"+minorVersion);  
        log.info("backcenterSessionFilter init-----------serverInfo:"+serverInfo);  
        log.info("backcenterSessionFilter init-----------servletContextName:"+servletContextName);  
        log.info("backcenterSessionFilter init-----------sessionTimeout:"+sessionTimeout);  
    } 


	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException  {
		// TODO Auto-generated method stub
        
		HttpServletRequest request = (HttpServletRequest) req;  
        HttpServletResponse response = (HttpServletResponse) res;  
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");  
//        System.out.println("path-->"+path);
        boolean allowedPath = ALLOWED_PATHS.contains(path);  
        
        String uri=request.getRequestURI();
        boolean allowedFile = false;
        if(uri.contains(".css") || uri.contains(".js") || uri.contains(".png") || uri.contains(".gif") 
        		|| uri.contains(".jpg") || uri.contains(".woff") || uri.contains(".ttf") || uri.contains(".html")
        	){
            //如果发现是css或者js文件，直接放行
        	allowedFile = true;
        }
  
        if (allowedPath==true || allowedFile==true) {  
//            System.out.println("这里是不需要处理的url进入的方法："+request.getRequestURI());  
            chain.doFilter(req, res);  
            return;
        }  
        
        //System.out.println("这里是需要处理的url进入的方法："+request.getRequestURI());  
		

		if(request.getRequestURI().contains("manage")){
			response.sendRedirect("hello");
		}

		HttpSession session = request.getSession();
		
		boolean isAuthenticated = false;
		try {
			isAuthenticated = (boolean) session.getAttribute("isAuthenticated");
		} catch (NullPointerException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			this.toLogin(request, response);
			return;
		}
		
		if(isAuthenticated==true) {
			Object person = session.getAttribute("person");
			req.setAttribute("person", person);

            chain.doFilter(req, res);  
		}else {
        	System.out.println("未登录，跳转到登录界面！");
        	this.toLogin(request, response);
		}
        
		
//		httpRequest.getSession().invalidate();
//		System.out.println("doFilter..............................执行完成！");
		
//		HttpServletResponse resp = (HttpServletResponse) res;
//		resp.setStatus(200);
//		System.out.println("start: " + resp.getStatus());  // 过滤之前状态均为 200
//		res.getWriter().write("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//	    chain.doFilter(req, res);
//	    System.out.println("after: " + resp.getStatus());  // 实际响应 HTTP 状态	
        
        
	}

	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
	  
    private void toLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uri=request.getRequestURI();
        //判断是否为ajax
        if (isAjax(request)) {
        	System.out.println("backcenterSessionFilter.doFilter-->>ajax请求-->>"+uri);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            ResultData resultData = new ResultData();
            resultData.setCode(-999);
            resultData.setMsg("登录认证失效，请重新登录!");
            response.getWriter().write(JSONObject.toJSON(resultData).toString());
        } else {
        	System.out.println("backcenterSessionFilter.doFilter-->>非ajax请求-->>"+uri);
        	String from = request.getRequestURL().toString();
        	String contextPath = request.getServletContext().getContextPath();
        	response.sendRedirect(contextPath + LOGIN_URL + "?from="+from);
//    		request.getRequestDispatcher(LOGIN_URL).forward(request,response);
        }

    }
			
}
